package sbt.applogic2;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.WebElement;

import sbt.applogic.FilmHelper;
import sbt.model.Film;
import sbt.pages.AddFilmPage;
import sbt.pages.FilmPage;
import sbt.pages.InternalPage;

public class FilmHelper2 extends DriverBasedHelper implements FilmHelper {

  public FilmHelper2(ApplicationManager2 manager) {
    super(manager.getWebDriver());
  }

  @Override
  public void create(Film film) {
	   pages.internalPage.ensurePageLoaded()
	      .clickAddFilmLink()
	      .ensurePageLoaded()
    	.setTitleField(film.getTitle())
    	.setYearField(film.getYear())
    	.clickSubmitButton();
	   String pageURL = pages.filmPage.getURL();
	   if (pages.filmPage.waitPageLoaded()) {
	   	   int lastIndexOf = pageURL.lastIndexOf("&id=");
	   	   film.setId(pageURL.substring(lastIndexOf+4));
	   }
  }

  @Override
  public void delete(Film film) {
	if(pages.internalPage.gotoFilmPage(film))
	pages.filmPage.clickRemoveFilm();

  }
  
  @Override
  public void delete() {
 	pages.filmPage.clickRemoveFilm();

  }

  
  @Override
  public void logout() {
    pages.filmPage.ensurePageLoaded()
      .clickLogoutLink();
  }

 @Override
 public void clearSearch() throws Exception {
	pages.internalPage.clearSearch();
 }
  @Override
  public List<Film> search(String title) throws Throwable {
    pages.internalPage.clearSearch();
    pages.internalPage.setSearchText(title);
    List<Film> FilmList = new ArrayList<Film>();
    List<WebElement> PE = getPageElement("//div[@id='results']//div[starts-with(@alt,'"+title+"')]");
    int filmCount = 0;
    while (filmCount != PE.size()){
    	WebElement el = PE.get(filmCount);
    	//String filmtitle = el.getAttribute("title");
    	Film film = new Film();//.setTitle(filmtitle);
    	FilmList.add(filmCount, film);
    	filmCount++;
    }
     return FilmList;
    
  }
 @Override
 public FilmPage getFilmPage() {
	 return pages.filmPage.ensurePageLoaded();
 }

 @Override
 public AddFilmPage getAddFilmPage() {
	 return pages.addfilmPage.ensurePageLoaded();
 }
 @Override
 public List<WebElement> getPageElement(String xPath) {
	 return pages.internalPage.ensurePageLoaded().findPageElements(xPath);
 }

 }
